import 'dart:async';
import 'dart:convert';
import 'dart:developer';
import 'package:get/get.dart';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';

enum MqttConnectionState { connected, disconnected, connecting }

class MqttService extends GetxService {
  MqttServerClient? _client;
  final connectionState = MqttConnectionState.disconnected.obs;
  String brokerAddress = '';
  final String clientId = 'flutter_client_${DateTime.now().millisecondsSinceEpoch}';

  void setup(String address) {
    if (address.isEmpty) return;
    brokerAddress = address;
    List<String> parts = address.split(':');
    String server = parts[0];
    int port = parts.length > 1 ? int.tryParse(parts[1]) ?? 1883 : 1883;

    _client = MqttServerClient(server, clientId);
    _client!.port = port;
    _client!.keepAlivePeriod = 20;
    _client!.onConnected = _onConnected;
    _client!.onDisconnected = _onDisconnected;
    _client!.connectionMessage = MqttConnectMessage()
        .withClientIdentifier(clientId)
        .startClean()
        .withWillQos(MqttQos.atLeastOnce);
  }

  Future<void> connect() async {
    if (_client == null) return;
    connectionState.value = MqttConnectionState.connecting;
    try {
      await _client!.connect();
    } catch (e) {
      print('MQTT client exception - $e');
      disconnect();
    }
  }

  void disconnect() {
    _client?.disconnect();
    connectionState.value = MqttConnectionState.disconnected;
  }

  void publish(Map<String, dynamic> data) {
    if (connectionState.value != MqttConnectionState.connected) return;

    String payload = jsonEncode(data);
    final builder = MqttClientPayloadBuilder()..addString(payload);
    final topic = '/api/device/info';
    // payload = jsonEncode({
    //   "ib": [{"ma": 10035, "mi": 306, "rs": 89}],
    //   "gn": [
    //     {"at": "30.69154250", "on": "104.19308083", "la": " 104.2", "sa": 8},
    //     {"at": "30.69155383", "on": "104.19306917", "la": " 104.2", "sa": 8},
    //     {"at": "30.69156267", "on": "104.19305967", "la": " 104.2", "sa": 8},
    //     {"at": "30.69157100", "on": "104.19305533", "la": " 104.2", "sa": 8},
    //     {"at": "30.69156117", "on": "104.19305333", "la": " 104.2", "sa": 9}
    //   ],
    //   "im": "869530079109191",
    //   "el": 80,
    //   "t": 1752692393,
    //   "f": 5
    // });
    _client!.publishMessage(topic, MqttQos.atLeastOnce, builder.payload!);
    log('--- Publishing Message to $topic: $payload');
  }

  void _onConnected() {
    connectionState.value = MqttConnectionState.connected;
    log('MQTT Connected.');
  }

  void _onDisconnected() {
    connectionState.value = MqttConnectionState.disconnected;
    log('MQTT Disconnected.');
  }
}